<!-- nepm数据可视化 -->
<template>
    <!-- <div>charts</div> -->
    <div class="charts-root">
        <div class="tool">
            <el-form :inline="true" label-position="right" label-width="120">
                <el-form-item label="城市" prop="city">
                    <div class="city-border">
                        <chooseCity @clear="queryForm.city = ''" @changeCity="changeCity" @changeProvince="changeProvince">
                        </chooseCity>
                    </div>
                </el-form-item>
                <el-form-item label="时间" prop="date">
                    <el-date-picker v-model="queryForm.date" type="month" value-format="YYYY-MM" format="YYYY-MM"
                        placeholder="选择月份" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getCityData()">查询</el-button>
                    <!-- <el-button type="primary" @click=" getCityDataWeek(queryForm.city)">查询最近一周</el-button> -->
                </el-form-item>
            </el-form>
        </div>
        <div class="charts ">
            <div class="charts-son pie-view" style="width: 90%;" ref="pieRef" v-if="true"></div>
            <div class="charts-son" v-else>
                <!-- <h3 style="margin: 5px 0 0 5px;">{{ `${queryForm.city === '' ? '全国' : queryForm.city}污染等级次数统计` }}</h3> -->
                <el-empty description="该城市暂无数据" />
            </div>
            <div class="charts-son bar-view" style="width: 90%;" ref="barRef"></div>
            <!-- 省 -->
            <div class="charts-son radar-view" style="width: 90%;" ref="provinceRef"></div>
        </div>

    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, inject } from 'vue'
import { post } from '../../utils/index.ts'
const Message = inject('$message') as any

import chooseCity from "../common/chooseCity.vue";
const changeCity = (e: any) => {
    queryForm.city = e.name
}
const changeProvince = (e: any) => {
    queryForm.city = e
}


import * as echarts from 'echarts'
// type EChartsOption = echarts.EChartsOption;
const pieRef: any = ref(null) //饼图
const barRef: any = ref(null)//柱状图
const provinceRef: any = ref(null)//省份分

//AQI 三级以上（包含三级）即为超标
const color = ['#02E300', '#FFFF00', '#FF7E00', '#FE0000', '#98004B', '#7E0123']
let xAxis = {
    type: 'category',
    data: ['九月', '十月', '十一月', '十二月', '一月', '二月', '三月', '四月', '五月', '六月']
}
let yAxis = {
    type: 'value'
}

let barSeries = [
    {
        // name: '大于等于三级超标次数',
        // barWidth: '30%',

        type: 'bar',
        data: [2, 3, 5, 9, 4, 6, 8, 2, 3, 5]
    }
]
let barOption = reactive({
    xAxis,
    yAxis,
    title: {
        text: '某城市超标次数',
        left: 'center'
    },
    tooltip: {
        trigger: 'item',
        formatter: '{b} : {c}次'
    },
    legend: {
        top: '5%',
        left: 'center'
    },
    series: barSeries,
})

let series = [
    {
        name: '某城市空气污染情况',
        type: 'pie',

        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
            borderRadius: 10,
            borderColor: '#f2f3f5',
            borderWidth: 2
        },
        label: {
            show: false,
            position: 'center'
        },
        emphasis: {
            label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
            }
        },
        labelLine: {
            show: false
        },
        data: [
            { value: 0, name: '优(一级)' },
            { value: 0, name: '良(二级)' },
            { value: 0, name: '轻度污染(三级)' },
            { value: 0, name: '中度污染(四级)' },
            { value: 0, name: '重度污染(五级)' },
            { value: 0, name: '严重污染(六级)' },
        ]
    },
]
let option = reactive({
    title: {
        text: '某城市各空气污染等级出现次数统计',
        left: 'center'
    },
    tooltip: {
        trigger: 'item',
        formatter: '{a}: <br/>{b} : {c}次 ({d}%)'
    },

    legend: {
        top: '5%',
        left: 'center'
    },
    color,
    series,
})

let provinceSeries = [{
    type: 'bar',

    data: [],
}]
let provinceOption = reactive({
    xAxis: {
        type: 'category',
        data: []
    },
    title: {
        text: '全国按省超标次数',
        left: 'center'
    },
    tooltip: {
        trigger: 'item',
        formatter: '{b} : {c}次'
    },
    yAxis: {
        type: 'value'
    },
    legend: {
        top: '5%',
        left: 'center'
    },
    series: provinceSeries,

})

let pie: any = ''
let bar: any = ''
let province: any = ''


const pieInit = () => {

    if (pie != null && pie != "" && pie != undefined) {
        pie.dispose();//销毁
        console.log('销毁');

    }
    console.log('?');
    pie = echarts.init(pieRef.value)
    // console.log(pie);

    const pieOption = {
        ...option,
    }
    pie.setOption(pieOption)
}

const barInit = () => {
    if (bar != null && bar != "" && bar != undefined) {
        bar.dispose();//销毁
    }
    bar = echarts.init(barRef.value)
    bar.setOption(barOption)
}

const provinceInit = () => {
    if (province != null && province != "" && province != undefined) {
        province.dispose();//销毁
    }
    province = echarts.init(provinceRef.value)
    province.setOption(provinceOption)
}

const init = () => {
    if (pie != null && pie != "" && pie != undefined) {
        pie.dispose();//销毁
    }
    pie = echarts.init(pieRef.value)

    const pieOption = {
        ...option,
    }
    pie.setOption(pieOption)
    // const line = echarts.init(lineRef.value)
    // const bar = echarts.init(barRef.value)
    // const radar = echarts.init(radarRef.value)


    if (bar != null && bar != "" && bar != undefined) {
        bar.dispose();//销毁
    }
    bar = echarts.init(barRef.value)
    bar.setOption(barOption)

    if (province != null && province != "" && province != undefined) {
        province.dispose();//销毁
    }
    province = echarts.init(provinceRef.value)
    province.setOption(provinceOption)
    // pieOption.series[0].type='pie'
    // const lineOption = {
    //     ...option,
    //     // xAxis,
    //     // yAxis,
    // }
    // const barOption = {
    //     ...option
    // }
    // const radarOption = {
    //     ...option
    // }

    // line.setOption(lineOption)
    // bar.setOption(barOption)
    // radar.setOption(radarOption)
}

const chartsData = reactive({
    countData: []
})

const queryForm = reactive({
    city: '',
    date: '',
    isEmpty: false,//列表是否为空
})

const getCityDataWeek = async (city: string,) => {
    let url = '/sys/count/ListByDateWeek'
    let data = {
        city: city + '市',
    }
    let res: any = await post(url, data)
    if (res && res.code === 0) {
        if (res.list) {
            // if (res.list.length === 0) {
            //     queryForm.isEmpty = false
            //     return
            // } else {
            //     queryForm.isEmpty = true
            // }
            option.title.text = `${queryForm.city}各空气污染等级出现次数统计`
            chartsData.countData = res.list.map((k: any) => {
                series[0].data[k.aqi - 1].value = k.aqiCount
                return {
                    aqi: k.aqi,
                    count: k.aqiCount
                }
            })
        } else {
            Message.info(`数据错误`)
        }

        init()
    } else {
        Message.info(`${res.code}:${res.msg}`)
    }
}

const getCityData = async () => {
    let url = '/sys/count/list'
    let data = {
        ...queryForm,
        city: queryForm.city === '' ? null : queryForm.city
    }
    let res: any = await post(url, data)
    if (res && res.code === 0) {
        if (res.list) {
            if (res.list && res.list.length === 0) {
                queryForm.isEmpty = false
                return
            } else {
                queryForm.isEmpty = true

            }
            option.title.text = `${queryForm.city === '' ? '全国' : queryForm.city}各空气污染等级出现次数统计`
            chartsData.countData = res.list.map((k: any) => {
                series[0].data[k.aqi - 1].value = k.aqiCount
                return {
                    aqi: k.aqi,
                    count: k.aqiCount
                }
            })
            pieInit()
        } else {
            Message.info(`数据错误`)
        }

    } else {
        Message.info(`${res.code}:${res.msg}`)
    }
}

const getAqiCount = async () => {
    if (queryForm.city === '' || queryForm.date === '') {
        Message.info('请选择城市或时间')
        return
    }
    let url = '/sys/count/ListByDate'
    let data = {
        ...queryForm,
        city: queryForm.city + '市',
    }
    let res: any = await post(url, data)
    if (res && res.code === 0) {
        if (res.list) {
            // if (res.list.length === 0) {
            //     queryForm.isEmpty = false
            //     return
            // } else {
            //     queryForm.isEmpty = true
            // }
            option.title.text = `${queryForm.city}各空气污染等级出现次数统计`
            chartsData.countData = res.list.map((k: any) => {
                series[0].data[k.aqi - 1].value = k.aqiCount
                return {
                    aqi: k.aqi,
                    count: k.aqiCount
                }
            })
        } else {
            Message.info(`数据错误`)
        }
        init()
    } else {
        Message.info(`${res.code}:${res.msg}`)
    }
}

//拿过去十个月的超标次数
const Past10MouthData = async () => {
    const year = new Date().getFullYear()
    // const mouth = new Date().getMonth() + 1
    const arr: Array<string> = []
    if ((new Date().getMonth() + 1 - 10) < 0) {
        //要追到去年
        let nowMouth = new Date().getMonth() + 1
        let nowYear = year
        for (let i = 0; i < 10; i++) {
            if (nowMouth === 0) {
                nowMouth = 12
                nowYear--
            }
            let string = `${nowYear}-${nowMouth < 10 ? '0' + nowMouth : nowMouth}`
            arr.push(string)
            nowMouth--
        }
    } else {
        let nowMouth = new Date().getMonth() + 1
        for (let i = 0; i < 10; i++) {
            let string = `${year}-${nowMouth < 10 ? '0' + nowMouth : nowMouth}`
            arr.push(string)
            nowMouth--
        }
    }
    // console.log(arr);

    let data = {
        city: queryForm.city === '' ? null : queryForm.city,
        timeList: arr
    }
    let res: any = await post('/sys/count/ListByDate', data)
    if (res && res.code === 0) {
        barOption.title.text = `${queryForm.city === '' ? '全国' : queryForm.city}近十个月空气污染超标次数统计`
        barSeries[0].data = res.list
        xAxis.data = res.timeList
        barInit()
    } else {
        Message.info(`${res.code}:${res.msg}`)
    }
}

// const queryByProvinceForm = reactive({
//     province: ''
// })
//拿全国，按省份分
const getALLByprovince = async () => {
    let data = {
        // province: queryByProvinceForm.province
    }
    let res: any = await post('/sys/count/provinceList', data)
    if (res && res.code === 0) {
        provinceOption.xAxis.data = res.provinceList
        provinceSeries[0].data = res.countList
        provinceInit()
    } else {
        Message.info(`${res.code}:${res.msg}`)
    }
}



onMounted(() => {
    //拿时间
    let date = `${new Date().getFullYear()}-${(new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1}`
    queryForm.date = date

    // barInit()

    // getCityDataWeek(queryForm.city)
    getALLByprovince()
    getCityData()
    Past10MouthData()
})


</script>

<style scoped lang="scss">
.charts-root {
    padding: 10px 20px 0;
    box-sizing: border-box;

    .tool {
        padding: 10px 0;
        width: 100%;
        border-radius: 15px;
        // height: 50px;
        background-color: #fff;

        .city-border {
            height: 30px;
            padding: 0 10px;
            border: 1px solid #999;
            border-radius: 5px;
        }
    }

    .charts {
        display: flex;
        flex-direction: column;
        flex-wrap: wrap;
        justify-content: space-around;
        align-items: center;


        .charts-son {
            margin: 10px 0;
            width: 40%;
            // height: 700px;
            height: 360px;
            background-color: #fff;
            transition: 0.3s 0s linear box-shadow;

            // cursor: pointer;
            &:hover {
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
                transform: scale(1);
            }
        }


    }
}
</style>